#页面父类
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
import autoit,time

class PageBase(object):
    def __init__(self,driver,base_url):
        self.driver=driver
        self.base_url=base_url

    def open(self,pathUrl):
        self.driver.get(self.base_url+pathUrl)

    #定位某元素
    #loc=by,value
    def myfind_element(self,loc,isDebug=False):
        by=loc[0]
        value=loc[1]
        ele=self.driver.find_element(by,value)
        if isDebug:
            self.driver.execute_script("arguments[0].setAttribute('style','color:red;background: green; border: 2px solid red;')",ele)
        return ele


    def myfind_elements(self,loc):
        by=loc[0]
        value=loc[1]
        return self.driver.find_elements(by,value)



    #定位到某元素，并输入数据
    def input(self,loc,data,isDebug=False):
        ele=self.myfind_element(loc,isDebug)
        ele.send_keys(data)

    #定位到某元素，并点击
    def click(self,loc,isDebug=False):
        ele=self.myfind_element(loc,isDebug)
        ele.click()

    #清空并输入。不会触发失去焦点
    def clearAndInput(self,loc,data,isDebug=False):
        ele=self.myfind_element(loc,isDebug)
        ele.send_keys(Keys.CONTROL,"a")
        ele.send_keys(Keys.BACKSPACE)
        ele.send_keys(data)

    #清空。失去焦点
    def clear(self,loc):
        ele=self.myfind_element(loc)
        ele.clear()

    #选中单选按钮的某选项
    #<input type="radio" name="sex" value="M" >男
    def click_radio(self,name,value):
        ele=self.driver.find_element(By.CSS_SELECTOR,f"input[type='radio'][name='{name}'][value='{value}']")
        ele.click()

    #选中复选框中的几个选项
    def click_checkbox(self,name,targetValue):
        #<input type="checkbox" name="aihao" value="dalanqiu">打篮球
        all_options=self.driver.find_elements(By.CSS_SELECTOR,f"input[type='checkbox'][name='{name}']")
        for x in all_options:
            attr_value=x.get_attribute("value")
            status=x.is_selected()
            if attr_value in targetValue:
                if  not status:
                    x.click()
            else:
                if status:
                    x.click()


    #选中下拉列表的选项：根据选项的value属性
    def click_select_by_value(self,name,value):
        #select name="degree"
        ele=self.driver.find_element(By.CSS_SELECTOR,f"select[name='{name}']")
        haha=Select(ele)
        haha.select_by_value(value)


    #选中下拉列表的选项：根据选项的文本内容
    def click_select_by_text(self,name,text):
        ele = self.driver.find_element(By.CSS_SELECTOR, f"select[name='{name}']")
        haha = Select(ele)
        haha.select_by_visible_text(text)

    #输入某日期
    def input_date(self,loc,riqi):
        ele=self.myfind_element(loc)
        self.driver.execute_script(f"arguments[0].value='{riqi}'",ele)


    #文件上传。方法1:局限性
    def uploadFiles1(self,loc,filesPath):
        newPath = filesPath.replace(",", "\n")
        ele = self.myfind_element(loc)
        ele.send_keys(newPath)

    #文件上传：方法2:autoIT库
    def uploadFiles2(self,loc,filesPath):
        if filesPath=="" or filesPath is None:
            return

        newFilePath = ""
        a = filesPath.split(",")  # ["C:/A/haha.png","C:/A/heihei.png"]
        for x in a:
            newFilePath += '"' + x + '" '

        newFilePath = newFilePath.replace("/", "\\")

        # 通过Selenium让“打开”窗口出现，并加2秒延迟。
        ele = self.myfind_element(loc)
        ActionChains(self.driver).click(ele).perform()
        time.sleep(2)

        # //2.通过autoit库来实现上传
        autoit.win_wait("打开", 10)
        autoit.control_send("打开", "Edit1", newFilePath)
        autoit.control_click("打开", "Button1")


    #判断某元素是否存在
    def isEleExists(self,loc):
        try:
            self.myfind_element(loc)
            return True
        except Exception:
            return False

    #获取元素的某属性（去掉首尾空格）
    def getEleAttr(self,loc,attrName):
        ele=self.myfind_element(loc)
        return ele.get_attribute(attrName).strip()

    #获取元素的文本内容（去掉首尾空格）
    def getEleText(self,loc):
        ele=self.myfind_element(loc)
        return ele.text.strip()

    #切换到子网页：iframe
    def swicth_iframe(self,loc):
        ele_iframe=self.myfind_element(loc)
        self.driver.switch_to.frame(ele_iframe)

    #切回来父网页
    def switch_defaultIframe(self):
        self.driver.switch_to.default_content()

    # 函数功能：鼠标单击某元素loc
    def mouse_click(self, loc):
        ele = self.myfind_element(loc)
        ActionChains(self.driver).click(ele).perform()

    # 函数功能：鼠标双击某元素loc
    def mouse_dbclick(self, loc):
        ele = self.myfind_element(loc)
        ActionChains(self.driver).double_click(ele).perform()

    # 函数功能：鼠标悬停在某元素loc
    def mouse_moveToEle(self, loc):
        ele = self.myfind_element(loc)
        ActionChains(self.driver).move_to_element(ele).perform()

    #截图
    def savePng(self,serviceName,Key):
        nowTime=time.strftime("%Y%m%d%H%M%S")
        imgName=f"{serviceName}_{Key}_{nowTime}.png"
        self.driver.get_screenshot_as_file(f"./screen/{imgName}")
        return imgName #"登录_K001_20250402110315.png"

    # 根据窗口标题（可以给部分）来切到对应的窗口换
    def switch_windowByTitle(self, target_title):
        moren_handler = self.driver.current_window_handle
        flag = True #默认是找不到目标窗口
        allWindows = self.driver.window_handles
        for one in allWindows:
            self.driver.switch_to.window(one)
            currentTitle = self.driver.title
            if target_title in currentTitle:
                flag = False
                break
            time.sleep(1)
        if flag:
            self.driver.switch_to.window(moren_handler)

    # 根据窗口url（可以给部分）来切到对应的窗口换
    def switch_windowByUrl(self, target_url):
        moren_handler = self.driver.current_window_handle
        flag = True
        allWindows = self.driver.window_handles
        for one in allWindows:
            self.driver.switch_to.window(one)
            currentUrl = self.driver.current_url
            if target_url in currentUrl:
                flag = False
                break
            time.sleep(1)
        if flag:
            self.driver.switch_to.window(moren_handler)